package com.ailanyin.modules.flowable.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ailanyin.common.security.utils.SecurityUtil;
import com.ailanyin.modules.flowable.domain.WfCopy;
import com.ailanyin.modules.flowable.domain.bo.WfCopyBo;
import com.ailanyin.modules.flowable.domain.bo.WfTaskBo;
import com.ailanyin.modules.flowable.domain.vo.WfCopyVo;
import com.ailanyin.modules.flowable.mapper.WfCopyMapper;
import com.ailanyin.modules.flowable.service.IWfCopyService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/12/12 0012 上午 10:02
 */
@Service
public class WfCopyServiceImpl implements IWfCopyService {

    @Autowired
    private HistoryService historyService;
    @Resource
    private WfCopyMapper wfCopyMapper;

    @Override
    public WfCopyVo queryById(Long copyId) {
        return wfCopyMapper.selectByCopyId(copyId);
    }

    @Override
    public List<WfCopyVo> queryList(WfCopyBo wfCopy) {
        return wfCopyMapper.selectList(wfCopy);
    }

    @Override
    public Boolean makeCopy(WfTaskBo taskBo) {
        if (StrUtil.isBlank(taskBo.getCopyUserIds())) {
            // 若抄送用户为空，则不需要处理，返回成功
            return true;
        }
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(taskBo.getProcInsId()).singleResult();
        String[] ids = taskBo.getCopyUserIds().split(",");
        List<WfCopy> copyList = new ArrayList<>(ids.length);
        Long originatorId = SecurityUtil.getLoginUserId();
        String originatorName = SecurityUtil.getLoginNickname();
        String title = historicProcessInstance.getProcessDefinitionName() + "-" + taskBo.getTaskName();
        for (String id : ids) {
            Long userId = Long.valueOf(id);
            WfCopy copy = new WfCopy();
            copy.setTitle(title);
            copy.setProcessId(historicProcessInstance.getProcessDefinitionId());
            copy.setProcessName(historicProcessInstance.getProcessDefinitionName());
            copy.setDeploymentId(historicProcessInstance.getDeploymentId());
            copy.setInstanceId(taskBo.getProcInsId());
            copy.setTaskId(taskBo.getTaskId());
            copy.setUserId(userId);
            copy.setOriginatorId(originatorId);
            copy.setOriginatorName(originatorName);
            copy.setCreateTime(new Date());
            copyList.add(copy);
        }
        return wfCopyMapper.insertBatch(copyList) > 0;
    }
}
